<?php
declare(strict_types = 1);
namespace app\admin\controller;

use app\BaseController;
use app\common\model\mysql\AdminUser;
use app\admin\validate\AdminUser as ValidateAdminUser;
use think\facade\Env;
use think\facade\View;
use think\facade\Log;
use think\facade\Session;

class Login extends AdminBase
{

    const ADMIN_PWD_SALT = "sssss";

    public function initialize()
    {
        if ($this->isLogin()) {
            return $this->redirect(url('index/index'), 302);
        }
    }

    /**
     * 登录页面
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        return View::fetch();
    }

    public function encryption(string $str): string
    {
        return md5(self::ADMIN_PWD_SALT . $str);
    }

    public function md5()
    {
        $res = Session::get(config('admin.session_admin'));
        print_r($res);exit;
        //return $this->encryption('123456');
    }

    /**
     * 登录检查
     * @return \think\response\Json
     */
    public function check()
    {
        if (!$this->request->isAjax()) {
            return show(config('status.error'),'请求异常');
        }

        $username = $this->request->param("username", '', 'trim');
        $password = $this->request->param("password", '', 'trim');
        $captcha = $this->request->param("captcha", '', 'trim');

        $data = [
            'username' => $username,
            'password' => $password,
            'captcha' => $captcha,
        ];

        //validate验证
        $validate = new ValidateAdminUser();
        if (!$validate->check($data)) {
            return show(config('status.error'),$validate->getError());
        }

        try {
            $adminUserBusiness = new \app\admin\business\AdminUser();
            $result = $adminUserBusiness->login($data);
        } catch (\think\Exception $e) {
            return show(config('status.error'),$e->getMessage());
        }

        if ($result) {
            return show(config('status.success'),'登录成功');
        }

        //return show(config('status.success'),'登录成功');

    }
}